use crate::{
    http::{self, Body, Error},
    response::Response,
};
use std::convert::From;

pub trait IntoResponse {
    fn into_response(self) -> Response;
}

impl IntoResponse for &str {
    fn into_response(self) -> Response {
        let body = Body::from_string(self.to_string());
        Response { res: body.into() }
    }
}

impl IntoResponse for Error {
    fn into_response(self) -> Response {
        let body = Body::from(self.to_string());

        let mut res = http::Response::new(self.status());
        res.set_body(body);

        Response { res }
    }
}

impl<T, E> IntoResponse for Result<T, E>
where
    T: IntoResponse,
    E: IntoResponse,
{
    fn into_response(self) -> Response {
        match self {
            Err(e) => e.into_response(),
            Ok(o) => o.into_response(),
        }
    }
}

impl<T: IntoResponse> From<T> for Response {
    fn from(value: T) -> Self {
        T::into_response(value)
    }
}
